<?php

namespace App\Composers;

use Auth, Request, Route, DB, App;
use Illuminate\View\View;

use App\Repositories\Eloquent\RoleRepository as Role;
use App\Repositories\Eloquent\PermissionRepository as Permission;

use Illuminate\Support\Str;

class MenuComposer 
{ 

    protected $navbar, $parent;

    /**
     * 构造函数
     */
    public function __construct() 
    {
        $this->setMenus();
    }    


    public function getMenus() 
    {
        return $this->navbar;
    }


    public function compose(View $view) 
    {        
        $view->with([
            'navbar' => $this->getMenus(),
            'parent'=>$this->getParentID(),
        ]);
    }

    protected function getParentID()
    {
        $nav = Request::path();

        $nav = Str::replaceFirst('/', '-', $nav);

        $nav = Str::before($nav, '/');
        
        $result = \App\Models\Acl\Permission::where('name', $nav)->first();

        if(isset($result))
            return $result->parent;

        return 0;
    }

    protected function setMenus()
    {        
        $staff = Auth::guard('admin')->user();

        //管理员
        if( $staff->supervisor() ){
            $rows = \App\Models\Acl\Permission::where('status', STATUS_NORMAL)
                        ->orderBy('order', 'ASC')
                        ->get();
        }
        //非管理员
        else{
            //登录人员所拥有的权限
            $permission = $staff->getAllPermissions()->sortBy('order')->where('status', STATUS_NORMAL);
            //dd($permission);
            //拥有的权限所属父级菜单ID
            $pluck = $staff->getAllPermissions()->pluck('parent')->unique()->values()->all();
            
            //父级菜单集合
            $parent = \App\Models\Acl\Permission::whereIn('id', $pluck)->orderBy('order')->get();
            
            //父级与所属权限合并
            $rows = $permission->merge($parent);
        }        

        $this->navbar = self::getChildMenu($rows, 0);
    }


    public static function getChildMenu($data, $pid)
    {
        $tree = array();

        foreach($data as $key => $value) {

            if($value['parent'] == $pid) { 

                $value['child'] = self::getChildMenu($data, $value['id']);
                
                $tree[] = $value;
            }
        }
        return $tree;
    }

   
}